﻿using System;
using System.Collections.Generic;
using System.Linq;
using MoroMoro.Samples.ToDoList.Base.Application;
using MoroMoro.Samples.ToDoList.Base.Persistence;
using MoroMoro.Samples.ToDoList.Domain.ToDos;

namespace MoroMoro.Samples.ToDoList.Application.ToDos
{
    /// <summary>
    /// <see cref="ToDo.State">ToDo の状態</see>を戻すスクリプトです。
    /// </summary>
    [Serializable]
    internal sealed class ToDoReversionScript : CommitmentScript<ToDoReversionOutputs, ToDoReversionErrors>
    {
        /// <summary>
        /// <see cref="ToDoReversionScript"/> クラスの新しいインスタンスを初期化します。
        /// </summary>
        /// <param name="workspace">作業スペース。</param>
        /// <exception cref="System.ArgumentNullException">workspace が null です。</exception>
        public ToDoReversionScript(IWorkspace workspace)
            : base(workspace)
        {
            Targets = null;
            State = null;
        }


        /// <summary>
        /// 対象の <see cref="ToDo"/> の一覧を取得または設定します。
        /// </summary>
        public IEnumerable<ToDo> Targets
        {
            get;
            set;
        }

        /// <summary>
        /// 遷移先となる<see cref="ToDo.State">状態</see>。
        /// </summary>
        public ToDoState? State
        {
            get;
            set;
        }


        /// <inheritdoc/>
        protected override ExecutionResult ExecuteWork()
        {
            if (Targets == null)
            {
                throw new InvalidOperationException();
            }
            if (State == null)
            {
                throw new InvalidOperationException();
            }

            if (!Targets.All(new ToDoCanRevertSpecification(State.Value).Delegate))
            {
                return new ToDoReversionErrors
                {
                    ContainsToDoWhichCanNotRevert = true
                };
            }
            
            foreach (var target in Targets)
            {
                target.RevertTo(State.Value);
            }

            return new ToDoReversionOutputs();
        }
    }
}
